package com.lyw.forum.common.interceptor;

import com.lyw.forum.common.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${forum.login.url}")
    private String defaultUrl;

    /**
     * 拦截器设置前置处理逻辑
     * @return true 放行, false 拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String userToken = request.getHeader("user_token");
        log.info("从header中获取token:" + userToken);

        //校验URL是否正确
        if (!defaultUrl.startsWith("/")) {
            defaultUrl = "/" + defaultUrl;
        }

        if (userToken == null) {
            log.warn("用户未登录, 请先登录");
            //跳转到登录页面
            response.sendRedirect(defaultUrl);
            return false;
        }

        //校验token是否合法
        Claims claims = JWTUtils.parseToken(userToken);
        if (claims == null) {
            //拦截
            //跳转到登录页面
            response.sendRedirect(defaultUrl);
            return false;
        }

        //放行
        return true;
    }

}
